import base64
import pickle

from django_redis import get_redis_connection


def merge_carts(request):
    user = request.user
    if user.is_authenticated:
        redis_conn = get_redis_connection('carts')
        carts_base64 = request.COOKIES.get('carts')

        # 1,2 解码购物车
        if carts_base64:
            carts_dict = pickle.loads(base64.b64decode(carts_base64))
            # {sku_id:{"count":1, "selected":True}}
        else:
            carts_dict = {}
        # 1,3 合并
        for sku_id, count_selected in carts_dict.items():
            redis_conn.hset('carts_%s' % user.id, sku_id, count_selected['count'])
            if count_selected['selected']:
                redis_conn.sadd('selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%s' % user.id, sku_id)

        request.del_cookies = ['carts']
    else:
        pass
